﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

using VIT.Library;
using VIT.Library.Web;
using VIT.Library.Images;
using VIT.Web.Controls;
using VIT.DataHelper.DataAccess;
using VIT.Wedding;

namespace VIT.Web.Admin
{
    public partial class ArticleEdit : VIT.Web.UI.VITComponent
    {
        public string genOption = string.Empty;
        Provider.Article obj;

        protected void Page_Load(object sender, EventArgs e)
        {            
            obj = new Provider.Article();
            try
            {
                obj.Id = int.Parse(Request["sId"]);
            }
            catch
            {
                obj.Id = 0;
            }

            if (obj.Id == 0) ButtonInsert.Visible = true; else ButtonModify.Visible = true;      

            if (!IsPostBack)
            {
                loadLanguages();
                loadData();
                loadCategory();
            }
            loadArticleType(obj.Id);
        }

        #region Methods
        private void loadData()
        {
            obj.LanguageId = Session["language"].ToString();
            obj.GetSingle();

            if (obj.Id > 0)
            {
                lblId.Text = obj.Id.ToString();
                trId.Visible = true;
                ArticleTitle.Text = obj.Title;
                Brief.Value = obj.Brief;
                Contents.Value = obj.Contents;
                Tag.Text = obj.Tag;
                Orders.Text = obj.Orders.ToString();
                DisplayDate.ReadOnly = true;
                DisplayDate.DateTime = obj.DisplayDate;                
                Published.Checked = obj.Published;
                if (!string.IsNullOrEmpty(obj.Image))
                {
                    img.Visible = true;
                    img.ImageUrl = "~/Uploads/Images/Articles/Thumbs/" + obj.Image;
                    img.AlternateText = obj.Image;

                    imgDetail.Visible = true;
                    imgDetail.ImageUrl = "~/Uploads/Images/Articles/Details/" + obj.Image;
                    imgDetail.AlternateText = obj.Image;
                }
                
            }            
        }

        private void loadArticleType(int id)
        {
            Provider.ArticleType at = new Provider.ArticleType();
            at.LanguageId = obj.LanguageId;
            DataTable dt = at.GetAll();
            ListItem li;

            foreach (DataRow dr in dt.Rows)
            {
                li = new ListItem(dr["Title"].ToString(), dr["Id"].ToString());
                if (id > 0) if (obj.hasType(dr["Id"].ToString())) li.Selected = true;
                ArticleType.Items.Add(li);
            }

            //ArticleType at = new ArticleType();
            //at.LanguageId = Session["language"].ToString();
            //DataTable dt = at.GetAll();
            //dt.Columns.Add("Checked");            

            //for (int i=0; i< dt.Rows.Count; i++)
            //{
            //    if (id > 0) if (obj.hasType(dt.Rows[i]["Id"].ToString())) dt.Rows[i]["Checked"] = "checked";
            //}
            //rptTypes.DataSource = dt;
            //rptTypes.DataBind();
        }

        private void loadLanguages()
        {
            LanguageId.DataSource = new Provider.Language().getAll();
            LanguageId.DataTextField = "Name";
            LanguageId.DataValueField = "Id";
            LanguageId.DataBind();

            LanguageId.SelectedValue = Session["language"].ToString();
        }

        private void loadCategory()
        {
            Provider.Category cat = new Provider.Category();
            cat.LanguageId = Session["language"].ToString();
            this.genOption = cat.GetAll().GenTagOption("Id", "Title", "0", selected: obj.CategoryId.ToString());
        }

        private void save()
        {        
            var data = new Dictionary<dynamic, List<object>> {
                                                        {ArticleTitle, new List<object> {"required"}},
                                                        {Orders, new List<object> {"number"}}
                                                    };
            if (MainCore.checkData(data))
            {
                bool imgvalid = true;                
                if (fupImgDetail.HasFile)
                {
                    if (MainCore.checkFile(fupImgDetail.FileName, "isImage"))
                    {
                        string oldImg = img.AlternateText;
                        obj.Image = String.Format("{0:yyMMddhhmmss}", DateTime.Now) + System.IO.Path.GetExtension(fupImgDetail.FileName);
                        try
                        {
                            // save
                            fupImgDetail.SaveAs(URLBaseDir + "Uploads/Images/Articles/Details/" + obj.Image);
                            //fupImg.SaveAs(Server.MapPath("Uploads/Images/Articles/Details/" + obj.Image));

                            // delete Details
                            if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/Articles/Details/" + oldImg))
                                System.IO.File.Delete(URLBaseDir + "Uploads/Images/Articles/Details/" + oldImg);

                            if (fupImgAvar.HasFile)
                            {
                                // save
                                fupImgAvar.SaveAs(URLBaseDir + "Uploads/Images/Articles/Thumbs/" + obj.Image);
                                //fupImg.SaveAs(Server.MapPath("Uploads/Images/Articles/Details/" + obj.Image));
                            }
                            else new ResizeImage().Resize(URLBaseDir + "/Uploads/Images/Articles/Details/" + obj.Image, URLBaseDir + "/Uploads/Images/Articles/Thumbs/" + obj.Image, 150); 

                            // delete Thumbs
                            if (System.IO.File.Exists(URLBaseDir + "Uploads/Images/Articles/Thumbs/" + oldImg))
                                System.IO.File.Delete(URLBaseDir + "Uploads/Images/Articles/Thumbs/" + oldImg);
                        }
                        catch (System.NotSupportedException ex)
                        {
                            throw ex;
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }
                    else
                    {
                        imgvalid = false;
                        setTrueVisible(lblHinhKoDung);
                    }
                }
                else obj.Image = img.AlternateText;

                if (imgvalid)
                {
                    obj.CategoryId = Convert.ToInt32(Request["CategoryId"]);
                    obj.LanguageId = LanguageId.SelectedValue;
                    obj.Title = ArticleTitle.Text;
                    obj.Brief = Brief.Value.Trim();
                    obj.Contents = Contents.Value.Trim();
                    obj.Tag = Tag.Text;
                    if (Orders.Text!="")
                        obj.Orders = int.Parse(Orders.Text);
                    obj.Published = Published.Checked;
                    //obj.Type = Request["ArticleType"];                    
                    for (int i = 0; i < ArticleType.Items.Count; i++)
                    {
                        if (ArticleType.Items[i].Selected)
                        {
                            obj.Type += ArticleType.Items[i].Value + ",";
                        }
                    }
                    if (obj.Save()) setTrueVisible(lblThanhCong);
                    else setTrueVisible(lblThatBai);
                }                
            }
            else setTrueVisible(lblThatBai);
        }

        private void setTrueVisible(System.Web.UI.HtmlControls.HtmlGenericControl control)
        {
            lblThanhCong.Visible = false;
            lblThatBai.Visible = false;
            lblHinhKoDung.Visible = false;
            control.Visible = true;
        }
        #endregion

        #region
        protected void Save_Click(object sender, EventArgs e)
        {
            save();
            RedirectComponent("Article", "ArticleList");
        }

        protected void Apply_Click(object sender, EventArgs e)
        {
            save();
            loadData();
            loadCategory();
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            RedirectComponent("Article", "ArticleList");
        }

        protected void LanguageId_SelectedIndexChanged(object sender, EventArgs e)
        {
            Session["language"] = LanguageId.SelectedValue;
            loadData();
            loadCategory();
        }
        #endregion        
	}
}